package com.senjoeson.netlib.http;

import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author sunqiao
 * @date 2018/7/12 14:24
 */

public class OkHttpProcessor implements IHttpProcessor {


    /**
     * 执行流程
     * 初始化一个okhttpclient  相当于难道一个httpurlconnection
     * 然后
     */
    private OkHttpClient mOkHttpClient;

    public OkHttpProcessor() {
        mOkHttpClient = new OkHttpClient.Builder().build();
    }

    @Override
    public void post(String url, Map<String, Object> params, final CallBack iCallBack) {
        FormBody requestBody = getRequestBody(params);
        Request request = getRequeset("PUT", url, requestBody);
        mOkHttpClient.newCall(request).enqueue(new OkhttpCallBack(iCallBack));
    }

    @Override
    public void get(String url, Map<String, Object> params, CallBack iCallBack) {
        FormBody requestBody = getRequestBody(params);
        Request request = getRequeset("GET", url, requestBody);
        mOkHttpClient.newCall(request).enqueue(new OkhttpCallBack(iCallBack));
    }


    public Request getRequeset(String method, String url, RequestBody requestBody) {
        return new Request.Builder().method(method, requestBody).url(url).build();
    }

    public FormBody getRequestBody(Map<String, Object> params) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> objectEntry : params.entrySet()) {
            String key = objectEntry.getKey();
            builder.add(key, objectEntry.getValue().toString());
        }
        return builder.build();

    }

}
